<?php
namespace app\admin\model;

use think\Model;
use traits\model\SoftDelete;
use \app\admin\model\NavClass;
use \app\base\Tree;
use \app\admin\model\Syslog;

class Nav extends Model
{
    use SoftDelete;

    protected $deleteTime = 'deltime';

    static public function getNavClassListId()
    {
        $l=NavClass::select();
        $lst=array();
        foreach($l as $v){
            $lst[$v['id']]=$v;
        }
        return $lst;
    }

    static public function TreeList()
    {
        $nav_list=self::order('orderid asc')->select();
        $tree=Tree::Create_Tree_Html($nav_list,'parentid','navname',0);
        
        $classlist=self::getNavClassListId();

        $list=self::order('orderid asc')->select();
        $list2=Tree::Create_Tree($list,'parentid',0);
		if(is_array($list2)){
			foreach($list2 as $k=>$v){
				$list2[$v['id']]=$v;
				$level=count(array_filter(explode(',',$v['parentstr'])));
				if($level>=1){
					$list2[$v['id']]['navname_indent']=str_prefix('├', $v['level']-1, '&nbsp;&nbsp;&nbsp;&nbsp;');
				}else{
					$list2[$v['id']]['navname_indent']="";
				}
				if(isset($classlist[$v['classid']]['classname'])){
					$list2[$v['id']]['classname']=$classlist[$v['classid']]['classname'];
				}else{
					$list2[$v['id']]['classname']='默认分类';
				}
				$list2[$v['id']]['status_s']=($v['status']==0?'已启用':'已禁用');
			}
        }
        return [
            'classlist'=>$classlist,
            'nav_tree'=>$tree,
            'list'=>$list2
        ];
    }
    /*
        保存
    */
    static public function SaveData($data)
    {
        $data['picurl']=$data['picurl']??'';
        //生成$parentstr
        if($data['parentid']>=1){
            $parent=self::where('id',$data['parentid'])->find();
            $data['parentstr']=$parent['parentstr'].$data['parentid'].',';
        }else{
            $data['parentstr']=",0,";
        }
        $data['posttime']=time();
        if($data['id']>0){
            Syslog::Rec(1,"创建导航[".$data['navname']."]",0);
            return self::update($data)?\Result(0,'操作成功'):\Result(1,'操作失败');
        }else{
            unset($data['id']);
            Syslog::Rec(1,"更新导航[".$data['navname']."]",0);
            return self::create($data)?\Result(0,'操作成功'):\Result(1,'操作失败');
        }
    }
    /*
        排序
    */
    static public function Sort($data)
    {
        $Nav=new Nav;
        foreach($data['field_ids'] as $k=>$v){
            $list[]=['id'=>$v,'orderid'=>$data['orderid_ipt'][$k]];
        }
        Syslog::Rec(1,"更新导航排序",0);
        return $Nav->isUpdate()->saveAll($list);
    }    
}